package com.gxa.servlet.staffservlet;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.dao.staffdao.PageBean;
import com.gxa.pojo.Result;
import com.gxa.pojo.staff.UserStaff;
import com.gxa.service.staffservice.StaffService;
import com.gxa.service.staffservice.impl.StaffServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/selectByPageServlet")
public class SelectByPageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/json;charset=utf-8");
        //因为request.getreader（）方法只能读一次，采样下面几行代码
        BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
        StringBuilder json = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            json.append(inputStr);
        }
        String jsonString = json.toString(); //这是将json转化为字符串的形式
        //将json字符串转化对象
        ObjectMapper objectMapper = new ObjectMapper();
        PageBean pageBean = objectMapper.readValue(jsonString, PageBean.class);

        int currentPage = pageBean.getCurrentPage(); //获得的当前页数
        int row = pageBean.getRow(); //获得的每页记录数

        StaffService staffService = new StaffServiceImpl();
        int totalCount = staffService.getTotalCount(); //获取总记录数
        pageBean.setTotalCount(totalCount);    //设置总记录数
        //获取总页数
        int totalPage = staffService.getTotalPage(totalCount, row);
        pageBean.setTotalPage(totalPage);   //设置总页数
        //获取分页查询的员工列表
        Map<String,Integer> map = new HashMap<>();
        //这是分页的数据
        List<UserStaff> userByPage = staffService.getUserByPage(map, currentPage, row);
        pageBean.setList(userByPage);
        Map<String,Object> map2 = new HashMap<>();
        String fl = null;
        if (pageBean!=null && userByPage!=null){
            map2.put("result", Result.ok("success",pageBean));
            fl = objectMapper.writeValueAsString(map2);
        }else{
            map2.put("result",Result.error());
            fl = objectMapper.writeValueAsString(map2);
        }
        PrintWriter writer = response.getWriter();
        writer.write(fl); //响应状态
        writer.flush();     //刷新流
        writer.close();     //关闭流
        streamReader.close(); //关闭

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
